package com.wechat.android.app.ui.userinfo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wechat.android.app.R;
import com.wechat.android.app.db.UserHelper;
import com.wechat.android.app.entity.UserInfoModel;
import com.wechat.android.app.global.Constants;
import com.wechat.android.app.rxbus.RxBus;
import com.wechat.android.app.rxbus.event.CommonEvent;
import com.wechat.android.app.ui.BaseActivity;
import com.wechat.android.app.utils.MyLog;
import com.wechat.android.app.utils.PhoneUtils;
import com.wechat.android.app.utils.glide.GlideUtils;
import com.wechat.android.app.utils.glide.config.GlideCacheConfig;
import com.wechat.android.app.widget.ActionSheetDialog;
import com.wechat.android.app.widget.CustomFontTextView;
import com.wechat.android.app.widget.RoundImageView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by yang on 2018/1/18.
 */

public class UserInfoActivity extends BaseActivity {
    private static final int PHOTO_CARMERA = 1;
    private static final int PHOTO_PICK = 2;
    private static final int PHOTO_CUT = 3;
    private static final int UPDATE_USER_NAME = 4;
    @BindView(R.id.tv_head_img)
    CustomFontTextView tvHeadImg;
    @BindView(R.id.tv_nick_name_title)
    CustomFontTextView tvNickNameTitle;
    private File tempFile = new File(Environment.getExternalStorageDirectory() + GlideCacheConfig.GLIDE_CARCH_DIR, getPhotoFileName());

    //    图片上传命名
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    @BindView(R.id.head_img)
    RoundImageView headImg;
    @BindView(R.id.relative_user_portrait)
    RelativeLayout relativeUserPortrait;
    @BindView(R.id.tv_nickname)
    CustomFontTextView tvNickname;
    @BindView(R.id.rel_user_name)
    RelativeLayout relUserName;
    private UserInfoModel userInfoModel = null;
    private RxPermissions rxPermissions;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("\uD81B\uDF0A\uD81B\uDFC9\uD81B\uDF2F\uD81B\uDFC4\uD81B\uDFBE\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD1\uD81B\uDF04\uD81B\uDFD4");
        tvHeadImg.setText("\uD81B\uDF16\uD81B\uDFC4\uD81B\uDF07\uD81B\uDFD4\uD81B\uDF3B\uD81B\uDF58");
        tvNickNameTitle.setText("\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD1\uD81B\uDF1E\uD81B\uDF6A\uD81B\uDF0A\uD81B\uDF61");
        rxPermissions = new RxPermissions(UserInfoActivity.this);
        userInfoModel = UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this);
        if (userInfoModel != null) {
            setUserInfo(userInfoModel);
        }
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.relative_user_portrait, R.id.rel_user_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.relative_user_portrait:
                new ActionSheetDialog(UserInfoActivity.this)
                        .builder()
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("\uD81B\uDF3A\uD81B\uDFD4\uD81B\uDF3B\uD81B\uDF58", ActionSheetDialog.SheetItemColor.ThemeColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if ((Build.VERSION.SDK_INT >= 23)) {
                                            onClickAllPermission();
                                        } else {
                                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                            // 指定调用相机拍照后照片的储存路径
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                                            startActivityForResult(intent, PHOTO_CARMERA);
                                        }


                                    }
                                })
                        .addSheetItem("\uD81B\uDF43\uD81B\uDFBB\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD4", ActionSheetDialog.SheetItemColor.ThemeColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if ((Build.VERSION.SDK_INT >= 23)) {
                                            onClickWRITE();
                                        } else {
                                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                            startActivityForResult(intent, PHOTO_PICK);
                                        }

                                    }
                                }).show();
                break;
            case R.id.rel_user_name:
                Intent ti = new Intent(UserInfoActivity.this, UpdateUserNameActivity.class);
                ti.putExtra("userName", tvNickname.getText().toString().trim());
                startActivityForResult(ti, UPDATE_USER_NAME);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_CARMERA:
                try {
                    if (tempFile != null) {
                        startPhotoZoom(Uri.fromFile(tempFile), 150);
                    }
                } catch (Exception e) {

                }

                break;
            case PHOTO_PICK:
                try {
                    if (data != null) {
                        startPhotoZoom(data.getData(), 150);
                    }
                } catch (Exception e) {

                }

                break;
            case PHOTO_CUT:
                try {
                    if (null != data) {
                        setPicToView(data);
                        UpdateUserPortraits(tempFile.getPath(), "");
                    }
                } catch (Exception e) {

                }
                break;
            case UPDATE_USER_NAME:
                if (data != null) {
                    String userName = data.getStringExtra("userName");
                    MyLog.e("yang", "userName==" + userName);
                    if (!TextUtils.isEmpty(userName)) {
                        tvNickname.setText(userName);
                        UpdateUserPortraits("", userName);
                    }
                }
                break;
        }
    }


    //上传用户头像
    private void UpdateUserPortraits(String imgUrl, final String userName) {
        mMProgressDialog.showNoText();
        String url = Constants.APP_API_BASE + Constants.API_UPDATE_USER_INFO;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(UserInfoActivity.this).getUserId() + "");
        params.setMultipart(true);
        if (!TextUtils.isEmpty(userName)) {
            params.addBodyParameter("name", userName);
        }
        try {
            MyLog.e("yang", "imgUrl==" + imgUrl);
            if (!TextUtils.isEmpty(imgUrl)) {
                params.addBodyParameter("file", new FileInputStream(new File(imgUrl)), "img/jpg", getPhotoFileName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "result==" + result);
                String data = PhoneUtils.checkResponseFlag(UserInfoActivity.this, result);
                if (!TextUtils.isEmpty(userName)) {
                    userInfoModel.setName(userName);
                }

                if (data != null && !TextUtils.isEmpty(data)) {
                    userInfoModel.setLogo(data);

                }
                UserHelper.getInstance().setUserInfoModel(userInfoModel);
                RxBus.getDefault().post(Constants.RXBUS_CODE_REFRESH_USERINFO, new CommonEvent("刷新用户信息"));
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mMProgressDialog.dismiss();
            }
        });


    }


    //    打开相机权限和存储权限
    public void onClickAllPermission() {
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            // 指定调用相机拍照后照片的储存路径
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                            startActivityForResult(intent, PHOTO_CARMERA);

                        } else {
                            mMStatusDialog.show("\uD81B\uDF2F\uD81B\uDF71\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF04\uD81B\uDFD6\uD81B\uDF1E\uD81B\uDF51\uD81B\uDFB9\uD81B\uDF43\uD81B\uDFBB", null);
                        }
                    }
                });

    }


    public void onClickWRITE() {
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {

                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, PHOTO_PICK);

                        } else {
                            mMStatusDialog.show("\uD81B\uDF2F\uD81B\uDF71\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF04\uD81B\uDFD6\uD81B\uDF1E\uD81B\uDF51\uD81B\uDFB9\uD81B\uDF43\uD81B\uDFBB", null);
                        }
                    }
                });

    }

    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap UserPortraitbitmap = bundle.getParcelable("data");
            headImg.setImageBitmap(UserPortraitbitmap);
            saveCropPic(UserPortraitbitmap);
        }
    }

    // 把裁剪后的图片保存到sdcard上
    private void saveCropPic(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fis = null;
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        try {
            fis = new FileOutputStream(tempFile);
            fis.write(baos.toByteArray());
            fis.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void setUserInfo(UserInfoModel userInfoModel) {
        tvNickname.setText(userInfoModel.getName());
        if (!TextUtils.isEmpty(userInfoModel.getLogo())) {
            GlideUtils.loadImage(UserInfoActivity.this, userInfoModel.getLogo(), headImg, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.icon_miaowen, R.mipmap.icon_miaowen);
        } else {
            headImg.setImageResource(R.mipmap.icon_miaowen);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
